const app = getApp()
var http = require('../../utils/http.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    coupons: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.initData()
  },
  /**
   * 加载数据
   */
  initData:function(){
    var ths = this;
    wx.showLoading({ title: '加载中' });
    var params = {
      url: "/api/coupon",
      data: {
        limit: 12
      },
      method: "GET",
      callBack: function (res) {
        if(res.data.length < 1){
          return
        }
        res.data.forEach(e => {
          e['btnDisabled'] = false;
          e['btnName'] = '立即领取'
        })
        ths.setData({
          coupons: res.data
        });
        wx.hideLoading();
      }
    };
    http.request(params);
  },
  received(event){
    // 领取优惠券
    if(app.globalData.userInfo == null){
      wx.showToast({
        title: "请登录后重新操作",
        icon: "none",
      });
      return
    }
    const userId = wx.getStorageSync('userId')
    var couponId = event.currentTarget.dataset.value;
    wx.showLoading({ title: '加载中' });
    var ths = this;
    var url = "/"+userId+"/coupon/"+couponId;
    var params = {
      url: url,
      method: "POST",
      callBack: function (res) {
        ths.data.coupons.forEach(e=>{
          if(couponId == e.id){
            e.btnName = '已经领取'
            e.btnDisabled = true
          }
        })
        ths.setData({
          coupons: ths.data.coupons
        });
        wx.hideLoading();
      }
    };
    http.request(params);
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.initData()  
  },
})